package com.xk857.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.xk857.aliyun.AliBaseBean;
import com.xk857.domain.Result;
import com.xk857.enums.ResultEnum;
import com.xk857.exception.DefaultException;
import com.xk857.properties.AliyunProperties;
import lombok.extern.java.Log;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * @author cv大魔王
 * @version 1.0
 * @date 2021/7/24 22:51
 */
@Log
@Component
public class AliyunUtils {

    @Autowired
    private AliBaseBean aliBaseBean;

    @Autowired
    private AliyunProperties aliyunProperties;

    public void sendMsg(String phone, String code) {
        Client client = null;
        try {
            client = aliBaseBean.createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(aliyunProperties.getSignature())
                    .setTemplateCode(aliyunProperties.getRegisterCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            log.info("[阿里云短信发送，" + sendSmsResponse.body.message + "] 手机号码：" + phone + " 验证码：" + code);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传图片文件
     *
     * @param file MultipartFile文件对象
     * @return
     */
    public Result uploadFileToOss(AliBaseBean base, AliyunProperties properties, MultipartFile file) {
        // 上传文件所在目录名，当天上传的文件放到当天日期的目录下。
        String folderName = "simple_efficient/" + DateFormatUtils.format(new Date(), "yyyyMMdd");
        // 保存到 OSS 中的文件名，采用 UUID 命名。
        String fileName = UUID.randomUUID().toString().replace("-", "");
        // 从原始文件名中，获取文件扩展名
        String fileExtensionName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        // 文件在 OSS 中存储的完整路径
        String filePath = folderName + "/" + fileName + fileExtensionName;

        OSS ossClient = base.getOssClient();

        // 上传文件到OSS 并响应结果
        PutObjectResult putObjectResult = null;
        try {
            putObjectResult = ossClient.putObject(properties.getBucketName(), filePath, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        ResponseMessage response = putObjectResult.getResponse();
        if (response == null) {
            // 上传成功 返回上传文件的访问完整路径
            return new Result(ResultEnum.UPLOAD_SUCCESS, properties.getBucketDomain() + filePath);
        } else {
            // 上传失败，OOS服务端会响应状态码和错误信息
            String errorMsg = "响应的错误状态码是【" + response.getStatusCode() + "】，" + "错误信息【" + response.getErrorResponseAsString() + "】";
            log.info("【上传图片出错】" + errorMsg);
            return new Result(ResultEnum.UPLOAD_ERROR, errorMsg);
        }
    }

    /**
     * 上传图片文件根据电脑位置
     *
     * @param oldFilepath 文件路径
     * @return 文件路径
     */
    public String uploadFileToOssByPath(AliBaseBean base, AliyunProperties properties, String oldFilepath) {
        // 上传
        // 上传文件所在目录名，当天上传的文件放到当天日期的目录下。
        String folderName = "simple_efficient/" + DateFormatUtils.format(new Date(), "yyyyMMdd");
        // 保存到 OSS 中的文件名，采用 UUID 命名。
        String fileName = UUID.randomUUID().toString().replace("-", "");
        // 从原始文件名中，获取文件扩展名
        String fileExtensionName = ".png";
        // 文件在 OSS 中存储的完整路径
        String filePath = folderName + "/" + fileName + fileExtensionName;

        OSS ossClient = base.getOssClient();
        try {
            // 上传文件到OSS 并响应结果
            PutObjectRequest putObjectRequest = new PutObjectRequest(properties.getBucketName(), filePath, new File(oldFilepath));
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            ResponseMessage response = putObjectResult.getResponse();
            if (response == null) {
                // 返回上传文件的访问完整路径
                return properties.getBucketDomain() + filePath;
            } else {
                throw new DefaultException("文件上传失败");
            }
        } catch (Exception e) {
            throw new DefaultException("文件上传失败");
        }
    }

    /**
     * 根据文件url删除
     *
     * @param fileUrl
     */
    public Result delete(AliBaseBean base, AliyunProperties properties, String fileUrl) {
        // 去除文件 url 中的 Bucket域名
        String filePath = fileUrl.replace(properties.getBucketDomain(), "");

        OSS ossClient = base.getOssClient();
        try {
            // 删除
            ossClient.deleteObject(properties.getBucketName(), filePath);
            return new Result(ResultEnum.DELETE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultEnum.DELETE_ERROR);
        }
    }

}
